package com.jonsnowsword.wifiassistant;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class WifiPassword {
	public List<Wifi> Read() 
	{ 
		List<Wifi> wifiInfos=new ArrayList<Wifi>(); 
		Process process = null; 
		DataOutputStream dataOutputStream = null; 
		DataInputStream dataInputStream = null; 
		StringBuffer wifiConf = new StringBuffer(); 
		try { 
			process = Runtime.getRuntime().exec("su"); 
			dataOutputStream = new DataOutputStream(process.getOutputStream()); 
			dataInputStream = new DataInputStream(process.getInputStream()); 
			dataOutputStream .writeBytes("cat /data/misc/wifi/*.conf\n"); 
			dataOutputStream.writeBytes("exit\n");
			dataOutputStream.flush(); 
			InputStreamReader inputStreamReader = new InputStreamReader( dataInputStream, "UTF-8"); 
			BufferedReader bufferedReader = new BufferedReader( inputStreamReader); 
			String line = null;
			while ((line = bufferedReader.readLine()) != null) 
			{ 
				wifiConf.append(line); 
			} 
			bufferedReader.close(); 
			inputStreamReader.close(); 
			process.waitFor(); 
		} 
		catch (Exception e) 
		{ 
			e.printStackTrace();
			return wifiInfos;
		} 
		finally 
		{ 
			try { 
				if (dataOutputStream != null) {
					dataOutputStream.close(); 
					} 
				if (dataInputStream != null) {
					dataInputStream.close();
					} 
				if (process != null) {
					process.destroy(); 
						} 
				
				}
			catch (Exception e) 
			{ 
				e.printStackTrace();
				return wifiInfos;
			} 
		}	 
		Pattern network = Pattern.compile("network=\\{([^\\}]+)\\}", Pattern.DOTALL);
		Matcher networkMatcher = network.matcher(wifiConf.toString() );
		while (networkMatcher.find() ) { 
			String networkBlock = networkMatcher.group();
			Pattern ssid = Pattern.compile("ssid=\"([^\"]+)\"");
			Matcher ssidMatcher = ssid.matcher(networkBlock); 
			if (ssidMatcher.find() ) { 
				Wifi wifiInfo=new Wifi();
				wifiInfo.Ssid=ssidMatcher.group(1);
				Pattern psk = Pattern.compile("psk=\"([^\"]+)\""); 
				Matcher pskMatcher = psk.matcher(networkBlock);
				if (pskMatcher.find() ) { 
					wifiInfo.Password=pskMatcher.group(1); 
					wifiInfo.setCapabilities("WPA");
					} 
				else {
					Pattern wepkey = Pattern.compile("wep_key0=\"([^\"]+)\""); 
					Matcher wep_keyMatcher = wepkey.matcher(networkBlock);
					if(wep_keyMatcher.find())
					{
						wifiInfo.Password=wep_keyMatcher.group(1); 
						wifiInfo.setCapabilities("WEP");
					}
					else
					{
						wifiInfo.Password="empty"; 
						wifiInfo.setCapabilities("");
					}
				}
				wifiInfo.setIsUserRecord(0);
				wifiInfos.add(wifiInfo);
				} 
			} 
		return wifiInfos; 
		} 
	}

